/*
 * @Description: 本地储存操作
 * @Author: Cxy
 * @Date: 2023-06-28 10:54:37
 * @LastEditors: Cxy
 * @LastEditTime: 2024-05-06 11:17:13
 * @FilePath: \blogAdmin\play\src\utils\storage.ts
 */

/**
 * storage 操作
 */
export const storageRead = (key: string | number) => {
  return JSON.parse(localStorage.getItem(String(key)) as string)
}

export const storageSet = (keyLocal: string | number, value: any, key?: string | number) => {
  let localData: any = value
  if (key) {
    localData = JSON.parse(localStorage.getItem(String(keyLocal)) as string)
    localData[String(key)] = value
  }
  localStorage.setItem(String(keyLocal), JSON.stringify(localData))
}

/**
 * cookie 操作
 */
export const cookieRead = (key: string): string | null => {
  if (!key || !cookieHas(key)) return null
  return decodeURIComponent(
    document.cookie.replace(
      new RegExp(`(?:(?:^|.*;)\\s*${encodeURIComponent(key).replace(/[-.+*]/g, '\\$&')}\\s*\\=\\s*([^;]*).*$)|^.*$`),
      '$1'
    )
  )
}

export const cookieSet = <T extends number | string | Date>(
  key: string,
  value: string,
  expT: T,
  path = import.meta.env.VITE_BASE,
  domain = location.hostname,
  secure = false
): boolean => {
  if (!key || /^(?:expires|max-age|path|domain|secure)$/i.test(key)) return false
  let expirTime = ''
  if (expT instanceof Date) {
    expirTime = `; expires=${expT.toUTCString()}`
  } else if (typeof expT === 'number') {
    expirTime =
      expT === Number.POSITIVE_INFINITY
        ? '; expires=Fri, 31 Dec 9999 23:59:59 GMT'
        : // js不支持通过 max-age 来设置过期时间
          `; expires=${new Date(Date.now() + expT * 1000).toUTCString()}`
  } else if (typeof expT === 'string') {
    expirTime = `; expires=${expT}`
  }
  try {
    document.cookie =
      `${encodeURIComponent(key)}=${encodeURIComponent(value)}${expirTime}` +
      `${domain || `; domain=${domain}`}${path || `; path=${path}`}${secure ? '; secure' : ''}`
    return true
  } catch (error) {
    console.error('Failed to set cookie:', error)
    return false
  }
}

export const cookieRemove = (key: string, path = import.meta.env.VITE_BASE, domain = location.hostname): boolean => {
  if (!key || !cookieHas(key)) return false
  return cookieSet(key, '', new Date(0), path, domain)
}

export const cookieHas = (key: string): boolean => {
  return new RegExp(`(?:^|;\\s*)${encodeURIComponent(key).replace(/[-.+*]/g, '\\$&')}\\s*\\=`).test(document.cookie)
}
